import {
    getBusinessInfo,
    toast
} from 'nc-lightapp-front';
import CommonAction from './common';
import setInitValue from '../../../public/functions/setInitValue';

let businessInfo = getBusinessInfo() || {};
let tmpKeyMap = {
    key: {
        tempKey: '',
        index: 0
    }
};
let test = null;
let test2 = null;
export default class FormAction extends CommonAction {
    constructor(comp, context) {
        super();
        this.comp = context || comp;
    }

    // 表单进入编辑态
    toEditStatus = async (formValue, editType) => {
        const {props} = this.comp;
        const {form, dispatch, button, emp, meta} = props;
        //const template = meta.getMeta();

        // 表单进入编辑
        form.setFormStatus('card', 'edit');
        // 按钮进入编辑的按钮
        await dispatch({
            type: 'emp/update',
            payload: {
                addPageStatus: 'edit'
            }
        });

        if (formValue) {
            if (editType === 'add') {
                setInitValue(props, 'card', formValue)
            }
            form.setAllFormValue({
                card: formValue
            });
        }

        /*// 展开子表
        template['formrelation']['card'].map((item) => {
            form.openArea(item);
        });


        setTimeout(() => {
            meta.setMeta(this.deepCopy(template));
        }, 100);*/

    }

    // 表单进入浏览态
    toBrowseStatus = (formValue) => {
        const {props} = this.comp;
        const {form, dispatch, button, emp, meta, cardPagination} = props;
        const template = meta.getMeta();

        // 如果不是来自审批中心则展示
        let showButton = !emp.fromApprove;

        let billState = 'init';
        let billId = '';
        // 表单进入编辑
        form.setFormStatus('card', 'browse');
        // 填充表单的值
        if (formValue) {
            form.setAllFormValue({
                card: formValue
            });
            billId = formValue.rows[0].values['pk_partmng'].value;
            billState = formValue.rows[0].values['approve_state'].value;
        } else {
            let allValues = form.getAllFormValue('card').rows[0].values
            billState = allValues['approve_state'].value;
            billId = allValues['approve_state'].value;
        }
        // 按钮进入编辑的按钮
        dispatch({
            type: 'emp/update',
            payload: {
                addPageStatus: 'browse'
            }
        });

        // 隐藏掉一些按钮
        button.setButtonVisible({
            add: showButton,
            search: false,
            aux_func: true,
            print: true,
            batchAdd: false,
            refresh: showButton,
            edit: (!showButton && ['3', '2'].includes(billState)) || ['-1'].includes(billState),
            del: showButton && ['-1'].includes(billState),
            copy: showButton && ['0'].includes(billState),
            commit: showButton && ['-1', '3'].includes(billState),
            recover: showButton && ['3'].includes(billState),
            execute: ['1', '102'].includes(billState),
            check_appr_opini: showButton,
            sendMsg: true,
            file: true,
            cardrpt: true
        });
        button.setButtonDisabled({
            edit: false,
            del: false,
            copy: false,
            commit: emp.fromApprove,
            recover: emp.fromApprove,
            aux_func: false,
            print: false,
            output: false
        });
        // 展开子表
        template['formrelation']['card'].map((item) => {
            form.openArea(item);
        });

        // 设置当前卡片id给卡片页的翻页使用
        setTimeout(() => {
            cardPagination.setCardPaginationId({
                id: billId,
                status: 1
            });
        }, 1);
    }

    // 进入到新增页面
    toAddPage = async () => {
        const {props} = this.comp;
        const {form, dispatch, emp, meta} = props;

        this.clearFormValue();

        try {
            let res = await dispatch({
                type: 'emp/checkToAddPage',
                payload: {
                    postData: {
                        pk_org: emp.orgValue.refpk
                    }
                }
            });
            if (res.success) {
                if (res.data && res.data.message) {
                    this.toast({
                        color: 'danger',
                        content: res.data.message
                    });
                    return;
                }
                let {
                    formData: {
                        card
                    },
                    psnItemMeta,
                    partinfo,
                    isBillCodeEditable
                } = res.data;

                let template = meta.getMeta();

                partinfo.items.map((item) => {
                    let {tempKey, index} = tmpKeyMap[item.attrcode] || {};
                    if (!item.queryCondition) {
                        item.queryCondition = {};
                    }

                    if (tempKey) {
                        if (template[tempKey].items[index].attrcode === item.attrcode) {
                            template[tempKey].items[index] = this.deepCopy(item);
                        } else {
                            template[tempKey].items.map((prevItem) => {
                                if (prevItem.attrcode === item.attrcode) {
                                    Object.assign(prevItem, item);
                                }
                            });
                        }
                    } else {
                        template.formrelation['card'].concat('card').map((key) => {
                            template[key].items.map((prevItem, index) => {
                                if (prevItem.attrcode === item.attrcode) {
                                    tmpKeyMap[item.attrcode] = {
                                        tempKey: key,
                                        index: index
                                    };
                                    Object.assign(prevItem, item);
                                }
                            })
                        });
                    }
                });

                if (psnItemMeta) {
                    template['psninfo'].items.map((item) => {
                        if (item.attrcode === 'pk_psnjob') {
                            Object.keys(psnItemMeta).forEach((key) => {
                                if (key !== 'queryCondition') {
                                    item[key] = psnItemMeta[key];
                                }
                            });
                        }
                    });
                    

                }

                template['card'].items.forEach((item) => {
                    if (item.attrcode === 'bill_code') {
                        item['disabled'] = !isBillCodeEditable;
                    }
                    if (item.attrcode === 'pk_psnjob') {
                        item['disabled'] = false;
                    }
                });
                await new Promise((resolve, reject) => {
                    meta.setMeta(template, resolve);
                });
                dispatch({
                    type: 'emp/update',
                    payload: {
                        page: 'add'
                    }
                });
                this.toEditStatus(card, 'add');
            }
        } catch (e) {
            console.log('toAddPageError', e);
        }
    }

    // 进入到修改页面
    toEditPage = async (selectedRows, formValue, others) => {
        const {props} = this.comp;
        const {form, dispatch, button, emp, meta} = props;

        this.clearFormValue();

        let postData = {
            billid: selectedRows[0].values['pk_partmng'].value,
            isapprove: emp.fromApprove,
            pk_org: emp.orgValue ? emp.orgValue.refpk : businessInfo.groupId
        };


        // 如果直接传入form表单的值，就直接进来了
        if (formValue) {
            dispatch({
                type: 'emp/update',
                payload: {
                    page: 'edit'
                }
            });
            this.toEditStatus(formValue, 'edit');

            if (others && 'isBillCodeEditable' in others) {
                form.setFormItemsDisabled('card', {
                    bill_code: !others.isBillCodeEditable,
                    pk_psnjob: true
                });
            }
            return;
        }

        let oneBillData = await this.getOneBillData(selectedRows);

        if (oneBillData === false) {
            return;
        }

        try {
            let res = await dispatch({
                type: 'emp/editBill',
                payload: {
                    postData: postData
                }
            });

            if (res.data && res.data.message) {
                this.toast({
                    color: 'danger',
                    content: res.data.message
                });
                return;
            }

            dispatch({
                type: 'emp/update',
                payload: {
                    page: 'edit'
                }
            });


            let {
                formData: {
                    head: {
                        card
                    }
                },
                isBillCodeEditable,
                disable = {},
                required = {},
                visible = {}
            } = res.data;

            let template = meta.getMeta();

            form.setFormItemsDisabled('card', {
                ...disable,
                bill_code: !isBillCodeEditable,
                pk_psnjob: false
            });
            form.setFormItemsRequired('card', {
                ...required
            });
            form.setFormItemsVisible('card', {
                ...visible
            });

            setTimeout(() => {
                this.toEditStatus(card);
            }, 50);
        } catch (e) {
            console.error(e);
        }
    }

    // 直接进入预览页面
    toBrowsePage = async (selectedRows, formValue) => {
        const {props} = this.comp;
        const {form, dispatch, button, emp, meta} = props;

        if (formValue) {
            this.toBrowseStatus(formValue);
            return;
        }


        try {
            let oneBillData = await this.getOneBillData(selectedRows);

            if (oneBillData) {
                dispatch({
                    type: 'emp/update',
                    payload: {
                        page: 'edit'
                    }
                });
            }

            this.toBrowseStatus(oneBillData.data.formData.head.card);
        } catch (e) {
            console.error('toBrowsePage', e);
        }
    }

    // 清空form
    clearFormValue = () => {
        const {props} = this.comp;
        const {form, dispatch, button, emp} = props;

        form.setAllFormValue({
            card: {
                rows: [{
                    values: {
                        memo: {
                            value: '',
                            display: ''
                        }
                    }
                }]
            }
        });
    }

    // 获取一条数据
    getOneBillData = async (selectedRows) => {
        const {props} = this.comp;
        const {form, dispatch, button, emp} = props;

        let postData = {
            billid: selectedRows[0].values['pk_partmng'].value,
            pk_org: emp.orgValue ? emp.orgValue.refpk : businessInfo.groupId
        };

        try {
            let res = await dispatch({
                type: 'emp/getOneBillData',
                payload: {
                    postData: postData
                }
            });

            if (res.success) {
                this.update({
                    addPageHistoryData: this.deepCopy(res.data.formData.head.card)
                });
                return res;
            }
        } catch (e) {
            console.error(e);
        }

        return false;
    }
}